<template>
  <div class="app-container">
    <FormCom class="form-search" ref="search" :columns="queryColumns" labelWidth="auto" v-show="showSearch"/>
    <div class="flr mb8">
      <div class="flbox">
        <el-button type="primary" plain @click="handleAdd">新增</el-button>
        <!--<el-button type="warning" plain @click="handleExport">导出</el-button>-->
      </div>
      <div class="flone">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
    </div>
    <TableCom :columns="tableColumns" :options="tableOptions" @getList="getList"></TableCom>

    <!-- 关联部门对话框 -->
    <el-dialog title="关联部门" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="字典标签">
          <el-input v-model="form.dictLabel" :disabled="true" />
        </el-form-item>
        <el-form-item label="关联部门" >
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <!--<el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>-->
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import indexVue from '@/config/indexVue';
  import { treeselect as deptTreeselect, roleDeptTreeselect } from "@/api/system/dept";

  const editColumns = [
    {text: "标签", name: "dictLabel", type: "input"},
    {text: "键值", name: "dictValue", type: "input"},
    {text: "排序", name: "dictSort", type: "input",value:"0"},
    {text: "状态", name: "status", type: "select",value:"0",options:"sys_normal_disable"},
  ]
  const editRule = {
    dictLabel: ["required"],
    dictValue: ["required"],
    dictSort: ["required"],
    status: ["required"],
  }

  export default {
    name: "WebCate",
    mixins:[indexVue],
    data() {
      this.actionName = "webCate";
      this.editColumns = editColumns;
      this.editRule = editRule;
      this.queryColumns = [
        { text:"标签",name:"dictLabel",type:"input",onKeyup:this.handleQuery},
        { text:"状态",name:"status",type:"select",options:"sys_normal_disable",onChange:this.handleQuery},
        { type:"label",searchButton:{listQuery:this.handleQuery, listReset:this.resetQuery}}
      ]
      this.tableColumns = [
        { type:"index",fixed:true },
        {"prop":"dictCode","label":"编码","width":100},
        {"prop":"dictLabel","label":"标签","minWidth":100},
        {"prop":"dictValue","label":"键值","minWidth":100},
        {"prop":"dictSort","label":"排序","minWidth":100},
        {"prop":"status","label":"状态","minWidth":100,options:"sys_normal_disable",template:"ColumnDict"},
        {"prop":"createTime","label":"创建时间","width":160},
        { label:"操作",prop:"_",width:"180",align:"center",fixed:"right",className:"",options:[
            {
              text:"修改",
              onClick:this.handleUpdate
            },
            {
              text:"删除",
              props:{class:'danger'},
              onClick:this.handleDelete
            },
            {
              text:"关联部门",
              onClick:this.handleRel
            },
          ]
        }
      ]
      //
      return {
        openDataScope:false,
        // 关联部门配置
        deptOptions:[],
        deptExpand: true,
        deptNodeAll: false,
        defaultProps: {
          children: "children",
          label: "label"
        },
        form:{
          dictLabel:'',
          remark:'',
          menuCheckStrictly: true,
          deptCheckStrictly: true,
        }
      }
    },
    mounted() {
      this.getList();
    },
    methods: {
      /** 查询列表 */
      getList() {
        let pm = this.$refs.search.getData();
        pm = Object.assign(_.pick(this.tableOptions,['pageNum','pageSize']),pm);
        pm.index = 1;
        pm.orderByColumn = "createTime";
        pm.isAsc = "desc";
        this.api(`webCate.list`,pm,this.tableOptions).then((response)=>{
          this.tableOptions.data = response.rows;
          this.tableOptions.total = response.total;
          this.$forceUpdate();
        })
      },
      /** 新增按钮操作 */
      handleAdd() {
        let pm = this.$refs.search.getData();
        this.dialogEdit({
          title:"新增",
          row:{cate:pm.cate,attachment:[]},
          PATH_SAVE:`webCate.add`,
          width:"540px",
          size:24,
          labelWidth:"6em",
          columns:editColumns,
          rules:editRule,
          formatter(d){
            d.files = JSON.stringify(d.attachment?.map((v)=>({name:v.name,url:v.url}))||[]);
            return d;
          }
        },()=>{
          this.getList();
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.dialogEdit({
          title:"编辑",
          row:row,
          PATH_SAVE:`webCate.update`,
          width:"540px",
          size:24,
          labelWidth:"6em",
          columns:editColumns,
          rules:editRule,
          formatter(d){
            d.files = JSON.stringify(d.attachment?.map((v)=>({name:v.name,url:v.url}))||[]);
            return d;
          }
        },()=>{
          this.getList();
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.dictCode;
        this.$modal.confirm(`是否确认删除【${ids}】的数据项？`).then(()=>{
          return this.api(`webCate.del`,ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
      },
      // ==================================
      // 关联部门
      handleRel(row){
        Object.assign(this.form,_.pick(row,['dictCode','dictValue','dictLabel','remark']));
        this.openDataScope = true;
        this.$nextTick(() => {
          let keys = (this.form.remark||'').split(',')
          roleDeptTreeselect(1).then(response => {
            this.deptOptions = response.depts;
            this.$refs.dept.setCheckedKeys(keys);
          })
        });
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        this.form.deptCheckStrictly = value ? true: false;
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys();
        return checkedKeys;
      },
      submitDataScope(){
        this.form.remark = this.getDeptAllCheckedKeys().join(',');
        this.api("webCate.update",this.form).then(()=>{
          this.$message.success('已保存')
          this.getList()
          this.cancelDataScope()
        })
      },
      cancelDataScope() {
        this.openDataScope = false;
      },
    }
  };
</script>
